//
//  Pay_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/5.
//
//


/*
 owner:cy
 update:2017年04月05日11:08:37
 info: 直供宝收银台
 */
import RxSwift
import UtilCore
import RickonCore
import BrandonCore

class Pay_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var pay_Tv: UITableView!
    var lastRow:NSInteger?
    /*----------------------------   自定义属性区域    ----------------------------*/
    /// orderid 和payid 必须有一个， 一般 orderid 是通过订单列表 未支付 点支付的时候跳转过来的
    var orderId:String?
    var orderSumAmount:String?
    var payid:String?
    
    var order_type:String?
    var giveid:String?
    
    var payTypes:[PayModel] = [
        PayModel(logo: "alipay", title: "支付宝支付", type: "2",hasSelected:true),
        PayModel(logo: "paywx", title: "微信支付",type: "0",hasSelected:false)
        
    ]
    /// 选择地址
    var payType:String = "2"
    
    ///是否验证金额
    var isCheck:String? = "0"
    
    
    var isEnable:Bool?
    
    var cofirmParam:(osCarts:NSString,iscart:String)?
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        NotificationCenter.default.addObserver(self, selector: #selector(Pay_Vc.getOrderPayResult(notification:)), name: NSNotification.Name(rawValue: AppConfig.notification.wxPayKey), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(Pay_Vc.getOrderPayResult(notification:)), name: NSNotification.Name(rawValue: AppConfig.notification.alipayKey), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(Pay_Vc.getispayEnable(notification:)), name: NSNotification.Name(rawValue: "isenable"), object: nil)
        ///隐藏滑动条
        self.pay_Tv.showsVerticalScrollIndicator = false
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        if Envs.isDebug {
            self.payTypes.append(PayModel(logo: "cszf", title: "测试支付",type: ""))
        }
        self.title = "\(AppConfig.appTitle)收银台"
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
    }
}
extension Pay_Vc{
    func confirmPayRequest() -> Bool {
        
        if  self.payid == nil && self.orderId == nil {
            showMsg("支付信息错误")
            return true
        }else{
            
            if let user = AppData.loginedUser{
                _ = "payrequest".openURL(["payid":self.payid ?? "","ordertype":self.order_type ?? "","paytype":self.payType,"orderamount":self.orderSumAmount ?? "","giveid":self.giveid ?? "","isCheck":self.isCheck ?? "","userid":user.userid ?? "","username":user.username == "" ? user.realname:user.username])
            }
            return false
        }
    }
    func getOrderPayResult(notification: NSNotification) {
        let rel = notification.object as? Dictionary<String,String>
        if let rel = rel{
            if let status = rel["status"] {
                _ = "paysuccesspage".openURL(["showtype":status])
            }
        }
    }
    func getispayEnable(notification: NSNotification) {
        self.isEnable = true
        self.pay_Tv.reloadData()
    }
}
// MARK: UITableViewDelegate
extension Pay_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.payTypes.count + 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "PayTotal_TCell", for: indexPath) as! PayTotal_TCell
            cell.totalPrice_Lb.text = self.orderSumAmount ?? ""
            return cell
        }else if indexPath.row == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "PayHeader_TCell", for: indexPath) as! PayHeader_TCell
            
            return cell
        }else if indexPath.row == self.payTypes.count + 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "Pay_Submit_TCell", for: indexPath) as! Pay_Submit_TCell
            cell.submit_Btn.isEnabled = isEnable ?? true
            cell.submit_Closure = {[unowned self] in
                return self.confirmPayRequest()
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "Pay_TCell", for: indexPath) as! Pay_TCell
            cell.item = self.payTypes[indexPath.row - 2]
            
            return cell
        }
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
}
// MARK: UITableViewDelegate
extension Pay_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        guard indexPath.row == 0 || indexPath.row == 1 || indexPath.row == self.payTypes.count + 2 else  {
            let currentItem = self.payTypes[indexPath.row - 2]
            for subItem  in self.payTypes {
                subItem.hasSelected = false
            }
            currentItem.hasSelected = true
            
            self.payType = currentItem.type
            currentItem.hasSelected = true
            self.pay_Tv.reloadData()
            return
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if indexPath.row == 0 {
            return 54
        }else if indexPath.row == 1{
            return 54
        }else if indexPath.row == self.payTypes.count + 2{
            return 54
        }else{
            
            return 80
        }
    }
}
